<template>
  <switch
    :checked="checked"
    :color="color"
    :disabled="getDisabled"
    @change="onChange"
    type="switch"
    style="transform: scale(0.8)"
  />
</template>

<script setup lang="ts">
  import { propTypes } from '@/utils/propTypes';
  import { computed, ref, watch } from 'vue';
  import { useFormItem } from '../hooks/useContext';

  const props = defineProps({
    modelValue: propTypes.bool.def(false),
    disabled: propTypes.bool.def(false),
    color: propTypes.string.def('#007aff'),
  });

  const emit = defineEmits(['update:modelValue', 'change']);

  const checked = ref(props.modelValue);
  const { getProps, setFormModel } = useFormItem(props);

  watch(
    () => getProps.value.modelValue,
    (newVal) => {
      let val = newVal;
      if (typeof newVal === 'string') {
        switch (newVal) {
          case '0':
          case 'false':
            val = false;
            break;
          case '1':
          case 'true':
            val = true;
            break;
        }
      }
      checked.value = val;
    },
    {
      immediate: true,
    },
  );

  const getDisabled = computed(() => getProps.value.disabled);

  function onChange(e: any) {
    setFormModel(e.detail.value);
    emit('update:modelValue', e.detail.value);
    emit('change', e);
  }
</script>

<style scoped></style>
